import { Form, Modal, Toast } from "@douyinfe/semi-ui";
import { useEffect, useRef, useState } from "react";
import { notificationCatchErr } from "../../lib/utils";
import robot from "../../api/robot";


export default function RobotEditPage({ visible, setVisible, data, setRefreshTable }) {
    const api = useRef();
    useEffect(() => {
        api.current?.setValues(data, true);
    }, [data]);
    const { Option } = Form.Select;
    const [loading, setLoading] = useState(false);

    const handleOk = () => {
        api.current.validate().then((values) => {
            setLoading(true)
            robot.save(values).then(({ data, msg }) => {
                setLoading(false)
                Toast.success(msg)
                setRefreshTable()
                setVisible(false);
            }).catch(e => {
                setLoading(false)
                notificationCatchErr("保存失败")(e)
            })
        }).catch((errors) => { console.log(errors); });
    };
    const handleCancel = () => {
        setVisible(false);
    };

    return <>
        <Modal
            title={data === null ? '创建机器人' : '修改机器人'}
            visible={visible}
            width={500}
            loading={loading}
            onOk={handleOk}
            onCancel={handleCancel}
            closeOnEsc={true}
        >
            <Form
                labelPosition={'left'}
                initValues={data}
                labelWidth={110}
                getFormApi={formApi => api.current = formApi}
                render={({ formState, formApi, values }) => (
                    <>
                        <Form.Select
                            field="robot_type"
                            rules={[
                                { required: true, message: '请选择机器人类型' },
                            ]}
                            label='机器人类型' style={{ width: '100%' }}>
                            <Option value="ROBOT_TYPE_FEISHU">飞书</Option>
                            <Option value="ROBOT_TYPE_QY_WECHAT">企微</Option>
                            <Option value="ROBOT_TYPE_DD">钉钉</Option>
                        </Form.Select>

                        <Form.Input
                            field='robot_name'
                            label='机器人名称'
                            placeholder={'请输入您的机器人名称'}
                            rules={[
                                { required: true, message: '请填写机器人名称' },
                            ]}
                        />

                        <Form.Input
                            field='webhook'
                            label='WebHook'
                            placeholder={'请录入WebHook'}
                            rules={[
                                { required: true, message: '请填写WebHook' },
                            ]}
                        />
                    </>
                )}>
            </Form>

        </Modal>
    </>
}